package cn.liziguo.tank.script.enemy;

import cn.liziguo.tank.config.GameConfig;
import cn.liziguo.tank.constants.GameEnum;
import cn.liziguo.tank.factory.BulletFactory;
import cn.liziguo.tank.script.BaseTankComponent;
import cn.liziguo.tank.util.CollidingUtils;
import cn.liziguo.tank.util.CoordinateUtils;
import cn.liziguo.tank.vector.Vector2;
import com.almasb.fxgl.core.math.FXGLMath;
import com.almasb.fxgl.core.math.Vec2;
import com.almasb.fxgl.core.util.LazyValue;
import com.almasb.fxgl.dsl.FXGL;
import com.almasb.fxgl.dsl.components.ExpireCleanComponent;
import com.almasb.fxgl.entity.Entity;
import com.almasb.fxgl.entity.EntityGroup;
import com.almasb.fxgl.physics.BoundingShape;
import javafx.geometry.Point2D;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.util.Duration;

import java.util.List;

/**
 * @author Liziguo
 * @date 2022/7/8 17:05
 */
public class EnemyComponent extends BaseTankComponent {

    public static final GameEnum[] BULLET_AIM = {GameEnum.BORDER, GameEnum.BRICK, GameEnum.STONE};

    protected final LazyValue<EntityGroup> listLazyBulletAimCollision = new LazyValue<>(() -> FXGL.getGameWorld().getGroup(BULLET_AIM));

    private static final Vec2[] VECTORS = {Vector2.UP, Vector2.DOWN, Vector2.LEFT, Vector2.RIGHT};

    private Entity infrared;

    public EnemyComponent() {
        super(GameConfig.ENEMY_SHOOT_CD, GameConfig.ENEMY_SKILL_CD);
        speed = GameConfig.ENEMY_SPEED;
    }

    @Override
    public void onAdded() {
        vector = FXGLMath.random(VECTORS).orElseThrow();
        Vector2.setRotation(vector, entity);
    }

    @Override
    public void onUpdate(double tpf) {
        // 如果地方前面有障碍 就随机扭转方向 最多掉n次 目的不要让敌人太蠢
        final int n = 1;
        List<Entity> list = isArmedShip ? listLazyCollisionShip.get().getEntitiesCopy() : listLazyCollision.get().getEntitiesCopy();

        // 每一帧有2.5%的几率改变方向 每秒60帧
        if (FXGLMath.randomBoolean(0.025)) {
            vector = FXGLMath.random(VECTORS).orElseThrow();
        }

        int i = 0;
        do {
            entity.translate(vector.x, vector.y);
            if (CollidingUtils.isColliding(entity, list) == null) {
                entity.translate(-vector.x, -vector.y);
                break;
            }
            entity.translate(-vector.x, -vector.y);
            vector = FXGLMath.random(VECTORS).orElseThrow();
        } while (i++ < n);

        // 设置敌人方向
        Vector2.setRotation(vector, entity);

        // 每一帧有1%的几率发射子弹 每秒60帧
        if (FXGLMath.randomBoolean(0.01)) {
            shoot();
        }
        if (skillCount > 0 && isPlayerInFront()) {
            skill();
            return;
        }

        moveForward();
    }

    @Override
    public void onShoot() {
        BulletFactory.createEnemyBullet(this);
    }

    public boolean isPlayerInFront() {
        if (infrared != null) {
            return false;
        }
        List<Entity> players = FXGL.getGameWorld().getGroup(GameEnum.PLAYER).getEntitiesCopy();
        for (Entity player : players) {
            Point2D point2D = CoordinateUtils.word2Local(entity, player.getCenter().getX(), player.getCenter().getY());
            final double distance = -point2D.getY();
            if (point2D.getY() < 0) {
                final double width = entity.getWidth() / 2;
                if (point2D.getX() >= -width / 2 && point2D.getX() <= width) {
                    List<Entity> aim = listLazyBulletAimCollision.get().getEntitiesCopy();
                    infrared = FXGL.entityBuilder()
                            .at(entity.getCenter())
                            .bbox(BoundingShape.box(0, distance))
                            .with(new ExpireCleanComponent(Duration.seconds(1.25)))
                            .buildAndAttach();
                    infrared.translate(0, -infrared.getHeight());
                    infrared.setRotationOrigin(new Point2D(0, infrared.getHeight()));
                    infrared.setRotation(entity.getRotation());

                    return CollidingUtils.isColliding(infrared, aim) == null;
                }
            }
        }
        return false;
    }

    @Override
    public void onSkill() {
        int infraredLength = Math.max(GameConfig.WIDTH, GameConfig.HEIGHT);
        Rectangle node = new Rectangle(1, infraredLength, Color.RED);
        // 设置偏移量
        Entity entity = this.entity;
        node.setTranslateY(-infraredLength + infrared.getHeight());

        infrared.getViewComponent().addChild(node);
        infrared = null;
        entity.setUpdateEnabled(false);

        FXGL.getGameTimer().runOnceAfter(() -> {
            if (entity.isActive()) {
                BulletFactory.createEnemyBulletPlus(this);
            }
        }, Duration.seconds(1));

//        FXGL.getGameTimer().runOnceAfter(() -> {
//            infrared.removeFromWorld();
//            this.infrared = null;
//        }, Duration.seconds(1.25));

        FXGL.getGameTimer().runOnceAfter(() -> {
            if (entity.isActive()) {
                entity.setUpdateEnabled(true);
            }
        }, Duration.seconds(1.5));
    }

}
